<?php

namespace App\Http\Middleware;


use App\Models\WxUsers;
use Closure;
use JWTAuth;
use App\Api\Helper\ReturnMessage;
use Illuminate\Contracts\Encryption\DecryptException;
class WapiMiddleware
{
    /**
     * Handle an incoming request.
     * @info    企业后台管理中间件
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //设置header 头
        /*header('Access-Control-Allow-Origin:*');//指定允许其他域名访问
        header('Access-Control-Allow-Methods:POST, GET, OPTIONS, PUT, DELETE');// 响应类型
        header('Access-Control-Allow-Headers:Content-Type, X-Auth-Token, Origin');
        header('Access-Control-Allow-Headers:x-requested-with,content-type');// 响应头设置*/

        //获取登录TOKEN
        $auth_token = $request->header("auth-token");
        $open_id = "";
        //解密TOKEN数据
        try {
            $token_data = decrypt($auth_token);
        } catch (DecryptException $e) {
            return ReturnMessage::success("登录失败",1003);
        }
        //校验数据
        if(empty($token_data['openid'])){
             return ReturnMessage::success("登录失败",1003);
        }
        $open_id = $token_data['openid'];
        /**
         * 处理数据
         */
        //获取用户数据
        $user = WxUsers::getInfo(['openid'=>$open_id,'token'=>$auth_token]);
        if(empty($user)){
            return ReturnMessage::success("登录失败",1003);
        }
        define('_USER_ID', $user['id']);
        define('_USER_TYPE', "wx");
        define('_OPEN_ID', $user['openid']);

        return $next($request);
    }



}
